package com.cx.healthex.base.utils;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.log4j.Logger;

import com.fasterxml.uuid.EthernetAddress;
import com.fasterxml.uuid.Generators;
import com.fasterxml.uuid.impl.TimeBasedGenerator;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

/**
 * @author peng
 */
public final class CommonUtils {

	private static Logger logger = Logger.getLogger(CommonUtils.class);

	public static final String DATA_FORMAT_ALL = "yyyy-MM-dd HH:mm:ss";
	public static final String DATA_FORMAT_DD = "yyyy-MM-dd";

	/**
	 * 生成1-9位随机数
	 *
	 * @param count
	 *            位数
	 * @return 返回count位随机数
	 */
	public static String getRandomNum(int count) {
		return RandomStringUtils.randomNumeric(count);
	}
	
	/**
	 * 主键生成器，基于时间戳+机器地址的
	 *
	 * @return 主键
	 */
	public static String getPrimaryKey() {
		EthernetAddress nic = EthernetAddress.fromInterface();
		TimeBasedGenerator uuidGenerator = Generators.timeBasedGenerator(nic);
		UUID uuid = uuidGenerator.generate();
		return uuid.toString().replaceAll("-", "").toLowerCase();
	}
	
	 /** 
     * 生成随机文件名：当前年月日时分秒+五位随机数 
     *  
     * @return 
     */  
    public static String getRandomFileName() {  
        SimpleDateFormat simpleDateFormat;  
        simpleDateFormat = new SimpleDateFormat("yyyymmddhhmmss");  
        Date date = new Date();  
  
        String str = simpleDateFormat.format(date);  
  
        Random random = new Random();  
  
        int num = random.nextInt(9999999);
        return str+num;
    } 

	/**
	 * @param date
	 * @return
	 */
	public static String date2String(Date date) {
		return date2String(date, DATA_FORMAT_ALL);
	}

	/**
	 * @param date
	 * @param dataFormat
	 *            默认为yyyy-MM-dd HH:mm:ss
	 * @return
	 */
	public static String date2String(Date date, String dataFormat) {
		if (null == date) {
			return null;
		}
		String dateFmt = DATA_FORMAT_ALL;
		if (StringUtils.isNotBlank(dataFormat)) {
			dateFmt = dataFormat;
		}
		DateFormat fmt = new SimpleDateFormat(dateFmt);
		return fmt.format(date);
	}

	/**
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static Date string2Date(String date) {
		return string2Date(date, DATA_FORMAT_ALL);
	}

	/**
	 * @param date
	 * @param dataFormat
	 *            默认为yyyy-MM-dd
	 * @return
	 * @throws ParseException
	 */
	public static Date string2Date(String date, String dataFormat) {
		String dateFmt = DATA_FORMAT_ALL;
		if (StringUtils.isNotBlank(dataFormat)) {
			dateFmt = dataFormat;
		}
		DateFormat fmt = new SimpleDateFormat(dateFmt);
		try {
			return fmt.parse(date);
		} catch (ParseException e) {
			logger.error(e.getMessage());
		}
		return null;
	}
	
	/**
     * 获得生成html文件模板路径
     *
     * @param request
     * @return
     */
	public static String getFtlHtmlPath(HttpServletRequest request) {
		String baseUrl = "/WEB-INF/ftl/html";
		return request.getSession().getServletContext().getRealPath("/")
				+ baseUrl;
	}

	/**
	 * 获得项目classPath
	 *
	 * @return
	 */
	public static String getClassPath() {
		String classPath = Thread.currentThread().getContextClassLoader()
				.getResource("/").getPath();
		if (SystemUtils.IS_OS_WINDOWS) {
			classPath = classPath.substring(1, classPath.length());
		}
		return classPath;
	}

	/**
	 * 获得项目classPath
	 *
	 * @return
	 */
	public static String getClassPath(String path) {
		String classPath = Thread.currentThread().getContextClassLoader()
				.getResource(path).getPath();
		if (SystemUtils.IS_OS_WINDOWS) {
			classPath = classPath.substring(1, classPath.length());
		}
		return classPath;
	}
	
	public static Map<String, String> retFailure() {
        return retFailure("操作失败");
    }
    
    public static Map<String, String> retFailure(String msg) {
        Map<String, String> res = new HashMap<String, String>();
        res.put("code", "0");
        res.put("msg", msg);
        return res;
    }
    
    public static Map<String, String> retSuccess() {
        return retSuccess("操作成功");
    }
    
    public static Map<String, String> retSuccess(String msg) {
        Map<String, String> res = new HashMap<String, String>();
        res.put("code", "1");
        res.put("msg", msg);
        return res;
    }
    
    /**
     * windows用命令调用其他程序
     * @param commandStr
     */
	public static String exeCmd(String commandStr) {
		logger.info(commandStr);
		BufferedReader br = null;
		try {
			Process p = Runtime.getRuntime().exec(commandStr);
			br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = br.readLine()) != null) {
				sb.append(line + "\n");
			}
			System.out.println(sb.toString());
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}
	
	//获取用户IP
	public static String getIpAddr(HttpServletRequest request) { 
		
		/*System.out.println("X-Real-IP--->"+request.getHeader("X-Real-IP"));
		
		System.out.println("x-forwarded-for--->"+request.getHeader("x-forwarded-for"));
		System.out.println("Proxy-Client-IP--->"+request.getHeader("Proxy-Client-IP"));
		System.out.println("WL-Proxy-Client-IP--->"+request.getHeader("WL-Proxy-Client-IP"));
		System.out.println("--->"+request.getRemoteAddr());*/
		
		/*Enumeration<String> en = request.getHeaderNames();
		while (en.hasMoreElements()) {
            String s = en.nextElement();
            System.out.println("name:"+s+"--values--->"+request.getHeader(s));
        }*/
		
			String ip = request.getHeader("X-Real-IP");
			ip = request.getRemoteAddr(); 
			if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
				ip = request.getHeader("x-forwarded-for");
			}
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("WL-Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getRemoteAddr(); 
	       } 
	       //System.out.println("user IP -- > "+ip);
	       ip = ip.substring(0,ip.lastIndexOf("."));
	       return ip; 
	   } 
	
	//获取用户IP
	public static String getRealIp(HttpServletRequest request) { 
		
		/*System.out.println("x-forwarded-for--->"+request.getHeader("x-forwarded-for"));
		System.out.println("Proxy-Client-IP--->"+request.getHeader("Proxy-Client-IP"));
		System.out.println("WL-Proxy-Client-IP--->"+request.getHeader("WL-Proxy-Client-IP"));
		System.out.println("--->"+request.getRemoteAddr());*/
		
	       String ip = request.getHeader("x-forwarded-for"); 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("WL-Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getRemoteAddr(); 
	       } 
	       return ip; 
	   } 
	
	public static boolean isLetter(char c) {   
	       int k = 0x80;   
	       return c / k == 0 ? true : false;   
	   }  
	  
	/** 
	 * 判断字符串是否为空 
	 * @param str 
	 * @return 
	 */  
	public static boolean isNull(String str){  
	    if(str==null||str.trim().equals("")||str.trim().equalsIgnoreCase("null")){  
	        return true;  
	    }else{  
	        return false;  
	    }  
	} 
	
	/**
	 * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1
	 * 
	 * @param String
	 *            s 需要得到长度的字符串
	 * @return int 得到的字符串长度
	 */
	public static int strLength(String s) {
		if (s == null)
			return 0;
		char[] c = s.toCharArray();
		int len = 0;
		for (int i = 0; i < c.length; i++) {
			len++;
			if (!isLetter(c[i])) {
				len++;
			}
		}
		return len;
	}
	
	
	/**
	 * Linux用命令调用其他程序
	 * @param commandStr
	 * @return
	 */
	public static String exec(String commandStr) {
		logger.info(commandStr);
		Process process;
		StringBuilder sb = new StringBuilder();
		InputStreamReader reader = null;
		InputStreamReader readErr = null;
		LineNumberReader line = null;
		LineNumberReader lineErr = null;
		try {
			process = Runtime.getRuntime().exec(commandStr);
			process.waitFor();
			reader = new InputStreamReader(process.getInputStream());
			readErr = new InputStreamReader(process.getErrorStream());
			line = new LineNumberReader(reader);
			lineErr = new LineNumberReader(readErr);
			logger.error("start reader exec error output......");
			String str = "";
			while ((str = lineErr.readLine()) != null) {
				sb.append(str).append("\n");
			}
			logger.error("+++++++++++++++++++++++++++++++++++++++\n" + sb.toString());
			sb = new StringBuilder();
			logger.info("start reader exec output......");
			while ((str = line.readLine()) != null) {
				sb.append(str).append("\n");
			}
			logger.info("+++++++++++++++++++++++++++++++++++++++\n" + sb.toString());
			return sb.toString();
		} catch (IOException e) {
			logger.info("+++++++++++++++--------------------------++++++++++++++++++++++++" + e.getMessage());
		} catch (InterruptedException e) {
			logger.info("+++++++++++++++--------------------------++++++++++++++++++++++++" + e.getMessage());
		} finally {
			if (lineErr != null) {
				try {
					lineErr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (readErr != null) {
				try {
					readErr.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (line != null) {
				try {
					line.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}

	
}
